package com.xinuo.numericalcontrolsystem.manager;


import android.graphics.RectF;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.Utils;
import com.xinuo.common.utils.LoopUtils;
import com.xinuo.numericalcontrolsystem.base.AppContext;
import com.xinuo.numericalcontrolsystem.constant.EquipmentType;
import com.xinuo.numericalcontrolsystem.constant.LightType;
import com.xinuo.numericalcontrolsystem.utils.AppSPUtils;
import com.xinuo.support.XnSupport;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import kotlin.Unit;
import kotlin.coroutines.Continuation;

/**
 * @author: czp
 * @date: 2024/9/12 10:53
 */
public class MqttManager {
    private static class Holder {
        public static MqttManager INSTANCE = new MqttManager();
    }

    public static MqttManager getInstance() {
        return MqttManager.Holder.INSTANCE;
    }

    private MQTTHelper mqttHelper;

    private MqttManager() {
        mqttHelper = new MQTTHelper(Utils.getApp(), "ws://www2.cjbeidou.com:80/mqtt", null, null);
    }

    public void connect() {
        if (mqttHelper.isConnected()) {
            return;
        }
        if (!NetworkUtils.isConnected()) {
            return;
        }
        String uuid = getUuid();
        if (StringUtils.isEmpty(uuid)) {
            return;
        }
        if (!AppSPUtils.isOpenMqtt()) {
            return;
        }
        mqttHelper.connect("device/" + uuid + "/electronic/command", true, mqttCallback);
    }

    private MqttCallback mqttCallback = new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {
            mqttHelper.connect("device/" + getUuid() + "/electronic/command", true, mqttCallback);
        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
            //收到消息
            String content = new String(mqttMessage.getPayload());
            LogUtils.d("收到消息：" + content);
            String[] items = content.split(",");
            if (items.length != 4) {
                return;
            }
            String uuid = items[0];
            if (!StringUtils.equals(uuid, getUuid())) {
                return;
            }
            String serialCode = items[1];
            String switchCode = items[2];
            String switchTo = items[3];
            Object obj = mqttCodeToEnum(switchCode);
            if (obj == null) {
                return;
            }
            if (obj instanceof LightType) {
                ModbusOutputManager.getInstance().setRemoteLightOn((LightType) obj, serialCode, switchCode, switchTo.equals("ON"));
            } else if (obj instanceof EquipmentType) {
                ModbusOutputManager.getInstance().setRemoteEquipmentOn((EquipmentType) obj, serialCode, switchCode, switchTo.equals("ON"));
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            LogUtils.d("发送成功");
        }
    };

    /**
     * 远程消息回执
     */
    public void messageReceipt(String serialCode, String switchCode, boolean switchTo, boolean isSuccess) {
        String uuid = getUuid();
        if (StringUtils.isEmpty(uuid)) {
            return;
        }
        String topic = "device/server/electronic/" + uuid;
        String content = uuid + "," + serialCode + "," + switchCode + "," + (switchTo ? "ON" : "OFF") + "," + (isSuccess ? 1 : 0);
        mqttHelper.publish(topic, content);
        LogUtils.d("发送消息：" + topic + "     " + content);
    }

    /**
     * 发送消息
     */
    public void publish(Object object, boolean value) {
        String uuid = getUuid();
        if (StringUtils.isEmpty(uuid)) {
            return;
        }
        String mqttCode = enumToMqttCode(object);
        if (StringUtils.isEmpty(mqttCode)) {
            return;
        }
        String topic = "device/server/electronic/" + uuid;
        String content = uuid + ",USERMODIFY," + mqttCode + "," + (value ? "ON,1" : "OFF,1");
        mqttHelper.publish(topic, content);
        LogUtils.d("发送消息：" + topic + "     " + content);
    }

    /**
     * 是否连接
     */
    public boolean isConnected() {
        return mqttHelper.isConnected();
    }

    public void disconnect() {
        mqttHelper.disconnect();
    }

    public String enumToMqttCode(Object object) {
        if (object instanceof LightType) {
            if (object == LightType.MAIN_LIGHTING) {
                return "MAIN_LIGHT";
            } else if (object == LightType.BIG_EMERGENCY_LIGHTING) {
                return "BIG_DANGER_LIGHT";
            } else if (object == LightType.SMALL_EMERGENCY_LIGHTING) {
                return "SMALL_DANGER_LIGHT";
            } else if (object == LightType.FOREMAST_LIGHT) {
                return "FOREMAST_LIGHT";
            } else if (object == LightType.MAIN_MAST_LIGHT) {
                return "MAIN_MAST_LIGHT";
            } else if (object == LightType.TAILLIGHT) {
                return "TAIL_LIGHT";
            }
        } else if (object instanceof EquipmentType) {
            if (object == EquipmentType.AIR_CONDITIONER) {
                return "AIR_CONDITIONER";
            } else if (object == EquipmentType.FREEZER) {
                return "ICE_TANK";
            } else if (object == EquipmentType.FOGHORN) {
                return "FOGHORN";
            } else if (object == EquipmentType.OIL_PUMP) {
                return "OIL_PUMP";
            } else if (object == EquipmentType.CUSTOM_SWITCH_1) {
                return "CUSTOM_SWITCH_1";
            } else if (object == EquipmentType.CUSTOM_SWITCH_2) {
                return "CUSTOM_SWITCH_2";
            }
        }
        return null;
    }

    public Object mqttCodeToEnum(String switchCode) {
        switch (switchCode) {
            case "MAIN_LIGHT":
                return LightType.MAIN_LIGHTING;
            case "BIG_DANGER_LIGHT":
                return LightType.BIG_EMERGENCY_LIGHTING;
            case "SMALL_DANGER_LIGHT":
                return LightType.SMALL_EMERGENCY_LIGHTING;
            case "FOREMAST_LIGHT":
                return LightType.FOREMAST_LIGHT;
            case "MAIN_MAST_LIGHT":
                return LightType.MAIN_MAST_LIGHT;
            case "TAIL_LIGHT":
                return LightType.TAILLIGHT;
            case "AIR_CONDITIONER":
                return EquipmentType.AIR_CONDITIONER;
            case "ICE_TANK":
                return EquipmentType.FREEZER;
            case "FOGHORN":
                return EquipmentType.FOGHORN;
            case "OIL_PUMP":
                return EquipmentType.OIL_PUMP;
            case "CUSTOM_SWITCH_1":
                return EquipmentType.CUSTOM_SWITCH_1;
            case "CUSTOM_SWITCH_2":
                return EquipmentType.CUSTOM_SWITCH_2;
            default:
                return null;
        }
    }

    public String getUuid() {
        String uuid = XnSupport.getInstance().getUuid();
        return uuid;
    }
}